<template>
  <div class="main_box" v-loading="pageLoading">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="beeperCode">
              <el-input v-model="filters.billNo" clearable placeholder="税号"></el-input>
            </el-form-item>
            <el-form-item prop="beeperName">
              <el-input v-model="filters.company" clearable placeholder="单位名称"></el-input>
            </el-form-item>
            <el-form-item prop="beeperMan">
              <el-input v-model="filters.fullName" clearable placeholder="开票人"></el-input>
            </el-form-item>
            <el-form-item prop="beeperPrice">
              <el-input v-model="filters.amount" clearable placeholder="开票金额/元"></el-input>
            </el-form-item>
            <el-form-item prop="beeperPhone">
              <el-input v-model="filters.phone" clearable placeholder="联系电话"></el-input>
            </el-form-item>
            <el-form-item prop="date">
              <el-date-picker
                v-model="filters.date"
                :clearable="true"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExport" @click="handleClickExport()">导出</el-button>
            <el-button size="mini" plain type="success" icon="el-icon-finished" v-has="permissionBatchOpen" @click="handleClickBatchOpen()">批量设置已开票</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <el-table :data="dataList" @selection-change="changeSelect" v-loading="listLoading" :fit="true" highlight-current-row>
        <el-table-column type="selection" width="50"></el-table-column>
        <el-table-column type="index" label="序号" width="50"></el-table-column>
        <el-table-column prop="company" label="单位名称" width="200"></el-table-column>
        <el-table-column prop="billNo" label="税号" width="200"></el-table-column>
        <el-table-column prop="fullName" label="开票人" width="100"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="150"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="amount" label="开票金额" width="120"></el-table-column>
        <el-table-column prop="remark" label="备注" width="150"></el-table-column>
        <el-table-column width="150" align="center" label="地址">
          <template slot-scope="scope">
            <span>{{ scope.row.provinceName }} - {{ scope.row.cityName }} - {{ scope.row.areaName }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="状态" lign="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{formatState(scope.row.state)}}
              </el-tag>
            </span>
          </template>
        </el-table-column> -->
        <el-table-column prop="createDate" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickViewAmount(scope.row)" size="mini">查看余额</el-button>
            <el-button v-has="permissionDelete" @click="handleClickDelete(scope.row)" size="mini">删除</el-button>
            <!--<el-dropdown trigger="click" size="small">
              <el-button type="primary">
                <i class="fa fa-list-ul"></i>更多
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>-->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>
  </div>
</template>

<script>
import * as message from '@/constants/message';
import FinanceApi from '@/api/finance/finance';

export default {
  name: 'InvoiceManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      dataList: [],
      selectIds: [],
      filters: {
        company: '',
        billNo: '',
        fullName: '',
        amount: '',
        phone: '',
        date: [],
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      listLoading: true,
      pageLoading: false, // 页面加载loading
      excelData: {}, // 备导出数据

      permissionAdd: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_SEE',
      permissionEdit: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_EDIT',
      permissionDelete: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_DELETE',
      permissionExport: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_EXPORT',
      permissionViewAmount: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_VIEW_AMOUNT',
      permissionBatchOpen: 'SYSTEM_MANAGER_FINANCE_INVOICE_LIST_BATCH_OPEN',
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  watch: {
    //to去哪，from从哪来
    $route(to, from) {
      if (from.path == '/finance/invoiceAdd') {
        this.listData();
      }
    },
  },
  methods: {
    init() {
      let _this = this;
      _this.initializationDate();
      _this.getTableHeight();
      _this.listData();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },

    // 初始化时间
    initializationDate() {
      let _this = this;
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      begin.setMonth(begin.getMonth() - 1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      _this.filters.date = [begin, end];
    },
    listData() {
      let _this = this;
      _this.listLoading = true;
      var startTime = '';
      var endTime = '';
      if (_this.filters.date) {
        (startTime = this.$Utils.formatDate(_this.filters.date[0], 'yyyy-MM-dd hh:mm:ss')), (endTime = this.$Utils.formatDate(_this.filters.date[1], 'yyyy-MM-dd hh:mm:ss'));
      }
      var cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
        company: _this.filters.company,
        billNo: _this.filters.billNo,
        fullName: _this.filters.fullName,
        amount: _this.filters.amount,
        phone: _this.filters.phone,
        startTime: startTime,
        endtime: startTime,
      };
      // 发送请求
      FinanceApi.listInvoice(cond)
        .then((data) => {
          this.dataList = data.data.list;
          this.page.pageTotal = data.data.total;
          _this.listLoading = false;
        })
        .catch((error) => {
          _this.listLoading = false;
          console.error(error);
        });
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        // 浏览器尺寸变化响应事件
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].reportId);
      }
      this.selectList = val;
    },
    // 过滤器
    formatState(cellValue) {
      if (cellValue == -1) {
        return '删除';
      } else if (cellValue == 0) {
        return '禁用';
      } else if (cellValue == 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue == -1) {
        return 'danger';
      } else if (cellValue == 0) {
        return 'info';
      } else if (cellValue == 1) {
        return 'success';
      }
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    resetForm() {
      var _this = this;
      _this.filters.company = '';
      _this.filters.billNo = '';
      _this.filters.fullName = '';
      _this.filters.amount = '';
      _this.filters.phone = '';
      _this.filters.date = [];
      _this.onSearch();
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listData();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listData();
    },
    handleClickViewAmount(row) {
      let cond = {
        idCard: row.idCard,
        fullName: row.fullName,
      };
      FinanceApi.getByCardAndName(cond).then((res) => {
        var msg =
          '姓 名：' +
          res.data.fullName +
          '<br/>' +
          '身份证：' +
          res.data.idCard +
          '<br/>' +
          '可开票金额：' +
          res.data.amount +
          '<br/>' +
          '待开票金额：' +
          res.data.amountWait +
          '<br/>' +
          '已开票金额：' +
          res.data.amountPass +
          '<br/>' +
          '创建时间：' +
          res.data.createDate;
        this.$alert(msg, '开 票 金 额 详 情', {
          confirmButtonText: '确定',
          dangerouslyUseHTMLString: true,
        });
      });
    },
    handleClickDelete(row) {
      let _this = this;
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let cond = {
          id: row.billId,
          state: -1,
        };
        FinanceApi.deleteInvoice(cond).then((res) => {
          _this.listData();
          _this.$Utils.notifySuccess();
        });
      });
    },
    // 新增税务发票
    handleClickAdd() {
      let _this = this;
      _this.$router.push('/finance/invoiceAdd');
    },
    handleClickEditor(val) {
      //编辑 进入新增页通过id来查找数据
      let _this = this;
      _this.$router.push({
        path: '/finance/invoiceEdit',
        query: { id: val.billId },
      });
    },
    // 批量已开票
    handleClickBatchOpen() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this
          .$confirm('确定批量设置为已开票吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            // 发送请求
            let cond = {
              ids: _this.selectIds,
              state: 1,
            };
            FinanceApi.auditInvoices(cond).then((res) => {
              if (res.status == 0) {
                _this.$Utils.notifySuccess();
              } else {
                _this.$notify.error({
                  title: message.TITLE_ERROR,
                  message: '操作失败',
                });
              }
            });
          })
          .catch(() => {
            console.error(error);
          });
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请至少选择一条记录！',
        });
      }
    },
    // 导出
    handleClickExport() {
      let _this = this;
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          _this.pageLoading = true;
          _this.onSearch(); // 导出前先刷新数据
          let cond = {
            company: _this.filters.company,
            billNo: _this.filters.billNo,
            fullName: _this.filters.fullName,
            amount: _this.filters.amount,
            phone: _this.filters.phone,
            startTime: this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss'),
            endTime: this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss'),
          };
          // 发送请求
          FinanceApi.getInvoiceExport(cond).then((res) => {
            if (res.data && res.data.length > 0) {
              let result = res.data;
              _this.excelData = result;
              _this.pageLoading = false;
              this.export2Excel();
            } else {
              _this.pageLoading = false;
              this.$notify.error({
                title: message.TITLE_ERROR,
                message: '未找到可导出的数据，请重新查询',
              });
            }
          });
        })
        .catch(() => {
          console.error(error);
        });
    },
    export2Excel() {
      let that = this;
      require.ensure([], () => {
        const { export_json_to_excel } = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        const tHeader = ['税号', '单位名称', '开票人', '邮箱', '联系电话', '开票金额/元', '省', '市', '区*详细地址', '创建时间', '备注']; // 导出的表头名
        const filterVal = ['billNo', 'company', 'fullName', 'email', 'phone', 'amount', 'provinceName', 'cityName', 'areaName', 'createDate', 'remark']; // 导出的表头字段名
        const list = that.excelData;
        const data = that.formatJson(filterVal, list);
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `康来税务发票数据_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
  },
};
</script>

<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
